//
//  ZHPopupMenuView.m
//  Pods
//
//  Created by Basic on 16/4/5.
//  Copyright © 2016年 zhihan. All rights reserved.
//
//

#import "ZHPopupMenuView.h"


#define kZHPopupMenuCell_IconSize                           20
#define kZHPopupMenuCell_TextMargin                         15.f
#define kZHPopupMenuCell_IconMargin                         15.f
#define kZHPopupMenuCell_SplitMargin                        10
#define kZHPopupMenuTableViewCellIndentifier            @"kZHPopupMenuTableViewCellIndentifier"



#pragma mark - ZHPopupMenuCell
@interface ZHPopupMenuCell ()
@property (nonatomic, strong) UIImageView   *iconImageView;
@property (nonatomic, strong) UILabel       *menuNameLabel;
@end

@implementation ZHPopupMenuCell
//MARK: - system
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:self.iconImageView];
        [self.contentView addSubview:self.menuNameLabel];
    }
    return self;
}
//MARK: - getter
-(UIImageView *)iconImageView
{
    if (!_iconImageView) {
        _iconImageView = [[UIImageView alloc]initWithFrame:CGRectZero];
        _iconImageView.backgroundColor = [UIColor clearColor];
        _iconImageView.contentMode = UIViewContentModeScaleAspectFit;
    }
    return _iconImageView;
}
-(UILabel *)menuNameLabel
{
    if (!_menuNameLabel) {
        _menuNameLabel = [[UILabel alloc]initWithFrame:CGRectZero];
        _menuNameLabel.backgroundColor = [UIColor clearColor];
        _menuNameLabel.font = [UIFont systemFontOfSize:14];
        _menuNameLabel.textColor = UIColor.blackColor;
        _menuNameLabel.textAlignment = NSTextAlignmentLeft;
    }
    return _menuNameLabel;
}
@end



#pragma mark - ZHPopupMenuView

@interface ZHPopupMenuView () <UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView                           *menuTableView;
@property (nonatomic, strong) CAShapeLayer                          *backgroundLayer;
@property (nonatomic, strong) NSArray<ZHPopupMenuItemModel *>       *menuArray;

@end

@implementation ZHPopupMenuView
#pragma mark - system
-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}
- (void)dealloc
{
#ifdef DEBUG
    NSLog(@"ZHPopupMenuView dealloc");
#endif
}

#pragma mark - getter
-(UITableView *)menuTableView
{
    if (!_menuTableView) {
        _menuTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _menuTableView.backgroundColor = [UIColor clearColor];
        _menuTableView.separatorColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.1];
        _menuTableView.layer.cornerRadius = kZHPopupMenuView_ArrowRadius;
        _menuTableView.scrollEnabled = NO;
        _menuTableView.clipsToBounds = YES;
        _menuTableView.delegate = self;
        _menuTableView.dataSource = self;
        [_menuTableView registerClass:[ZHPopupMenuCell class] forCellReuseIdentifier:kZHPopupMenuTableViewCellIndentifier];
        [self addSubview:_menuTableView];
    }
    return _menuTableView;
}
-(void)setShouldAutoScroll:(BOOL)shouldAutoScroll
{
    self.menuTableView.scrollEnabled = shouldAutoScroll;
}


#pragma mark - public
-(void)showWithFrame:(CGRect)frame withNameArray:(NSArray<ZHPopupMenuItemModel *> *)nameArray doneBlock:(void (^)(NSInteger, ZHPopupMenuItemModel *))doneBlock {
    self.frame = frame;
    _menuArray = nameArray;
    self.doneBlock = doneBlock;
    CGRect menuRect = CGRectMake(0, kZHPopupMenuView_MenuArrowHeight, self.frame.size.width, self.frame.size.height - kZHPopupMenuView_MenuArrowHeight);
    if (_arrowDirection == ZHPopupMenuDirectionDown) {
        menuRect = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height - kZHPopupMenuView_MenuArrowHeight);
    }
    [self.menuTableView setFrame:menuRect];
    [self.menuTableView reloadData];
    [self drawBackgroundLayerWithAnglePoint:self.anglePoint];
}
-(void)drawBackgroundLayerWithAnglePoint:(CGPoint)anglePoint
{
    if (_backgroundLayer) {
        [_backgroundLayer removeFromSuperlayer];
    }
    UIBezierPath *path = [UIBezierPath bezierPath];
    BOOL allowRoundedArrow = kZHPopupMenuView_AllowRoundedArrow;
    CGFloat offset = 2.f*kZHPopupMenuView_ArrowRadius*sinf(M_PI_4/2.f);
    CGFloat roundcenterHeight = offset + kZHPopupMenuView_ArrowRadius*sqrtf(2.f);
    CGPoint roundcenterPoint = CGPointMake(anglePoint.x, roundcenterHeight);
    
    switch (_arrowDirection) {
        case ZHPopupMenuDirectionUp:
        {
            //箭头朝上，需要显示箭头
            if (!self.hideArrow) {
                if (allowRoundedArrow) {
                    //允许圆角arrow
                    [path addArcWithCenter:CGPointMake(anglePoint.x + kZHPopupMenuView_MenuArrowWidth, kZHPopupMenuView_MenuArrowHeight - 2.f*kZHPopupMenuView_ArrowRadius) radius:2.f*kZHPopupMenuView_ArrowRadius startAngle:M_PI_2 endAngle:M_PI_4*3.f clockwise:YES];
                    [path addLineToPoint:CGPointMake(anglePoint.x + kZHPopupMenuView_ArrowRadius/sqrtf(2.f), roundcenterPoint.y - kZHPopupMenuView_ArrowRadius/sqrtf(2.f))];
                    [path addArcWithCenter:roundcenterPoint radius:kZHPopupMenuView_ArrowRadius startAngle:M_PI_4*7.f endAngle:M_PI_4*5.f clockwise:NO];
                    [path addLineToPoint:CGPointMake(anglePoint.x - kZHPopupMenuView_MenuArrowWidth + (offset * (1.f+1.f/sqrtf(2.f))), kZHPopupMenuView_MenuArrowHeight - offset/sqrtf(2.f))];
                    [path addArcWithCenter:CGPointMake(anglePoint.x - kZHPopupMenuView_MenuArrowWidth, kZHPopupMenuView_MenuArrowHeight - 2.f*kZHPopupMenuView_ArrowRadius) radius:2.f*kZHPopupMenuView_ArrowRadius startAngle:M_PI_4 endAngle:M_PI_2 clockwise:YES];
                }
                else {
                    //不允许圆角箭头
                    [path moveToPoint:CGPointMake(anglePoint.x + kZHPopupMenuView_MenuArrowWidth, kZHPopupMenuView_MenuArrowHeight)];
                    [path addLineToPoint:anglePoint];
                    [path addLineToPoint:CGPointMake( anglePoint.x - kZHPopupMenuView_MenuArrowWidth, kZHPopupMenuView_MenuArrowHeight)];
                }
            } else {
                [path moveToPoint:CGPointMake(kZHPopupMenuView_MenuRadius, kZHPopupMenuView_MenuArrowHeight)];
            }
            [path addLineToPoint:CGPointMake(kZHPopupMenuView_MenuRadius, kZHPopupMenuView_MenuArrowHeight)];
            [path addArcWithCenter:CGPointMake(kZHPopupMenuView_MenuRadius, kZHPopupMenuView_MenuArrowHeight + kZHPopupMenuView_MenuRadius) radius:kZHPopupMenuView_MenuRadius startAngle:-M_PI_2 endAngle:-M_PI clockwise:NO];
            [path addLineToPoint:CGPointMake( 0, self.bounds.size.height - kZHPopupMenuView_MenuRadius)];
            [path addArcWithCenter:CGPointMake(kZHPopupMenuView_MenuRadius, self.bounds.size.height - kZHPopupMenuView_MenuRadius) radius:kZHPopupMenuView_MenuRadius startAngle:M_PI endAngle:M_PI_2 clockwise:NO];
            [path addLineToPoint:CGPointMake( self.bounds.size.width - kZHPopupMenuView_MenuRadius, self.bounds.size.height)];
            [path addArcWithCenter:CGPointMake(self.bounds.size.width - kZHPopupMenuView_MenuRadius, self.bounds.size.height - kZHPopupMenuView_MenuRadius) radius:kZHPopupMenuView_MenuRadius startAngle:M_PI_2 endAngle:0 clockwise:NO];
            [path addLineToPoint:CGPointMake(self.bounds.size.width , kZHPopupMenuView_MenuRadius + kZHPopupMenuView_MenuArrowHeight)];
            [path addArcWithCenter:CGPointMake(self.bounds.size.width - kZHPopupMenuView_MenuRadius, kZHPopupMenuView_MenuRadius + kZHPopupMenuView_MenuArrowHeight) radius:kZHPopupMenuView_MenuRadius startAngle:0 endAngle:-M_PI_2 clockwise:NO];
            [path closePath];
            
        }
            break;
        case ZHPopupMenuDirectionDown:
        {
            //箭头朝下，需要显示箭头
            if (!self.hideArrow) {
                roundcenterPoint = CGPointMake(anglePoint.x, anglePoint.y - roundcenterHeight);
                if (allowRoundedArrow) {
                    //允许圆角arrow
                    [path addArcWithCenter:CGPointMake(anglePoint.x + kZHPopupMenuView_MenuArrowWidth, anglePoint.y - kZHPopupMenuView_MenuArrowHeight + 2.f*kZHPopupMenuView_ArrowRadius) radius:2.f*kZHPopupMenuView_ArrowRadius startAngle:M_PI_2*3 endAngle:M_PI_4*5.f clockwise:NO];
                    [path addLineToPoint:CGPointMake(anglePoint.x + kZHPopupMenuView_ArrowRadius/sqrtf(2.f), roundcenterPoint.y + kZHPopupMenuView_ArrowRadius/sqrtf(2.f))];
                    [path addArcWithCenter:roundcenterPoint radius:kZHPopupMenuView_ArrowRadius startAngle:M_PI_4 endAngle:M_PI_4*3.f clockwise:YES];
                    [path addLineToPoint:CGPointMake(anglePoint.x - kZHPopupMenuView_MenuArrowWidth + (offset * (1.f+1.f/sqrtf(2.f))), anglePoint.y - kZHPopupMenuView_MenuArrowHeight + offset/sqrtf(2.f))];
                    [path addArcWithCenter:CGPointMake(anglePoint.x - kZHPopupMenuView_MenuArrowWidth, anglePoint.y - kZHPopupMenuView_MenuArrowHeight + 2.f*kZHPopupMenuView_ArrowRadius) radius:2.f*kZHPopupMenuView_ArrowRadius startAngle:M_PI_4*7 endAngle:M_PI_2*3 clockwise:NO];
                } else {
                    //不允许圆角arrow
                    [path moveToPoint:CGPointMake(anglePoint.x + kZHPopupMenuView_MenuArrowWidth, anglePoint.y - kZHPopupMenuView_MenuArrowHeight)];
                    [path addLineToPoint:anglePoint];
                    [path addLineToPoint:CGPointMake( anglePoint.x - kZHPopupMenuView_MenuArrowWidth, anglePoint.y - kZHPopupMenuView_MenuArrowHeight)];
                }
            } else {
                [path moveToPoint:CGPointMake(kZHPopupMenuView_MenuRadius, anglePoint.y - kZHPopupMenuView_MenuArrowHeight)];
            }
            [path addLineToPoint:CGPointMake(kZHPopupMenuView_MenuRadius, anglePoint.y - kZHPopupMenuView_MenuArrowHeight)];
            [path addArcWithCenter:CGPointMake(kZHPopupMenuView_MenuRadius, anglePoint.y - kZHPopupMenuView_MenuArrowHeight - kZHPopupMenuView_MenuRadius) radius:kZHPopupMenuView_MenuRadius startAngle:M_PI_2 endAngle:M_PI clockwise:YES];
            [path addLineToPoint:CGPointMake( 0, kZHPopupMenuView_MenuRadius)];
            [path addArcWithCenter:CGPointMake(kZHPopupMenuView_MenuRadius, kZHPopupMenuView_MenuRadius) radius:kZHPopupMenuView_MenuRadius startAngle:M_PI endAngle:-M_PI_2 clockwise:YES];
            [path addLineToPoint:CGPointMake( self.bounds.size.width - kZHPopupMenuView_MenuRadius, 0)];
            [path addArcWithCenter:CGPointMake(self.bounds.size.width - kZHPopupMenuView_MenuRadius, kZHPopupMenuView_MenuRadius) radius:kZHPopupMenuView_MenuRadius startAngle:-M_PI_2 endAngle:0 clockwise:YES];
            [path addLineToPoint:CGPointMake(self.bounds.size.width , anglePoint.y - (kZHPopupMenuView_MenuRadius + kZHPopupMenuView_MenuArrowHeight))];
            [path addArcWithCenter:CGPointMake(self.bounds.size.width - kZHPopupMenuView_MenuRadius, anglePoint.y - (kZHPopupMenuView_MenuRadius + kZHPopupMenuView_MenuArrowHeight)) radius:kZHPopupMenuView_MenuRadius startAngle:0 endAngle:M_PI_2 clockwise:YES];
            [path closePath];
            
        }break;
        default:
            break;
    }
    
    _backgroundLayer = [CAShapeLayer layer];
    _backgroundLayer.path = path.CGPath;
    _backgroundLayer.fillColor = self.menuBgColor.CGColor;
    if (self.menuShadowColor) {
        _backgroundLayer.shadowColor = self.menuShadowColor.CGColor;
        _backgroundLayer.shadowOffset = CGSizeMake(0, 0.1);
        _backgroundLayer.shadowOpacity = 1;
        _backgroundLayer.shadowRadius = 1;
    }
    [self.layer insertSublayer:_backgroundLayer atIndex:0];
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.lineHeight;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.f;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _menuArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZHPopupMenuItemModel *menuItem = nil;
    if(indexPath.row <= self.menuArray.count-1){
        menuItem = self.menuArray[indexPath.row];
    }
    ZHPopupMenuCell *menuCell = [tableView dequeueReusableCellWithIdentifier:kZHPopupMenuTableViewCellIndentifier];
    menuCell.selectionStyle = UITableViewCellSelectionStyleNone;
    CGFloat margin = (self.lineHeight - kZHPopupMenuCell_IconSize)/2.f;
    CGRect iconImageRect = CGRectMake(kZHPopupMenuCell_IconMargin, margin, kZHPopupMenuCell_IconSize, kZHPopupMenuCell_IconSize);
    CGFloat menuNameX = iconImageRect.origin.x + iconImageRect.size.width + kZHPopupMenuCell_TextMargin;
    CGRect menuNameRect = CGRectZero;
    if (!menuItem.menuIcon) {
        menuNameRect = CGRectMake(0, 0, self.frame.size.width, self.lineHeight);
        menuCell.menuNameLabel.textAlignment = NSTextAlignmentCenter;
    }
    else{
        menuNameRect = CGRectMake(menuNameX, 0, self.frame.size.width - menuNameX - kZHPopupMenuCell_TextMargin, self.lineHeight);
        menuCell.iconImageView.frame = iconImageRect;
        menuCell.iconImageView.image = menuItem.menuIcon;
        menuCell.menuNameLabel.textAlignment = NSTextAlignmentLeft;
    }
    if (self.menuTitleFont) {
        menuCell.menuNameLabel.font = self.menuTitleFont;
    }
    menuCell.menuNameLabel.textColor = self.menuTitleColor;
    menuCell.menuNameLabel.frame = menuNameRect;
    menuCell.menuNameLabel.text = menuItem.menuName;
    if (menuItem.selectColor) {
        menuCell.menuNameLabel.textColor = menuItem.selectColor;
    }
    
    if (indexPath.row == _menuArray.count-1) {
        menuCell.separatorInset = UIEdgeInsetsMake(0, self.bounds.size.width, 0, 0);
    }
    else{
        menuCell.separatorInset = UIEdgeInsetsMake(0, kZHPopupMenuCell_SplitMargin, 0, 0);
    }
    return menuCell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ZHPopupMenuItemModel *itemModel = nil;
    if(indexPath.row <= self.menuArray.count-1){
        itemModel = self.menuArray[indexPath.row];
    }
    if (self.doneBlock) {
        self.doneBlock(indexPath.row, itemModel);
    }
}

@end
